package org.akomantoso.core.io.util;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.akomantoso.core.data.Count;
import org.akomantoso.core.data.ParliamentaryAnalysisTypeElement;
import org.akomantoso.core.data.Quorum;
import org.akomantoso.core.io.Input;
import org.akomantoso.core.io.InputConstants;

/**
 * @author <a href="mailto:jacques.militello@gmail.com">Jacques Militello</a>
 */
public final class ParliamentaryAnalysisTypeElementUtil {

	private ParliamentaryAnalysisTypeElementUtil() {
	}

	public static final Map<String, Instantiator<ParliamentaryAnalysisTypeElement>> MAP;

	private static ParliamentaryAnalysisTypeElement instantiate(String elementName) {

		final Instantiator<ParliamentaryAnalysisTypeElement> instatiator = MAP.get(elementName);
		if (instatiator == null) {
			throw new RuntimeException("Tag [" + elementName + "] not supported ParliamentaryAnalysisTypeElement ?!?");
		}
		return instatiator.instantiate();

	}

	public static void read(Input in, List<ParliamentaryAnalysisTypeElement> elements, final String localName)
			throws IOException {

		ParliamentaryAnalysisTypeElement element = null;

		while (true) {

			switch (in.getEventType()) {
			case InputConstants.START_ELEMENT:
				elements.add(element = instantiate(in.getLocalName()));
				element.readExternal(in);
				break;
			case InputConstants.END_ELEMENT:
				if (localName.equals(in.getLocalName())) {
					return;
				}
			}

			in.readNext();
		}
	}

	static {
		Map<String, Instantiator<ParliamentaryAnalysisTypeElement>> temp = new HashMap<String, Instantiator<ParliamentaryAnalysisTypeElement>>();

		temp.put(Count.ELEMENT, new Instantiator<ParliamentaryAnalysisTypeElement>() {
			public Count instantiate() {
				return new Count();
			}
		});

		temp.put(Quorum.ELEMENT, new Instantiator<ParliamentaryAnalysisTypeElement>() {
			public Quorum instantiate() {
				return new Quorum();
			}
		});

		MAP = Collections.unmodifiableMap(temp);
	}
}
